﻿#if UNITY_EDITOR
using UnityEditor;
#endif
using UnityEngine;
using System.Collections;
using System.Xml.Serialization;

namespace Hont.BlazingNodePackage
{
    public abstract class Value_BaseNode<T> : Node
    {
        string mName = "";

        /// <summary>
        /// In Node:    |
        ///                   |       ===========
        ///                   ----- =                       =
        ///                           =                       =
        ///                           ===========
        /// </summary>
        public bool IsInNode;
        [XmlIgnore]
        public T Value { get; set; }
        public virtual object SeriValue { get { return Value; } set { Value = (T)value; } }

        public override string Name { get { return mName; } }
        public override string Category { get { return "Variable"; } }

        protected abstract string InternalName { get; }


        public Value_BaseNode()
        {
            mName = InternalName;
        }

        protected override void Init()
        {
            base.Init();

            mInPortList.Clear();
            if (IsInNode)
                mInPortList.Add(new Port() { Host = this, Name = "In" });

            mOutPortList.Clear();
            if (!IsInNode)
                mOutPortList.Add(new Port() { Host = this, Name = Value == null ? "Out" : Value.ToString() });
        }

        public override IEnumerator Execute(Port port)
        {
            if (IsInNode)
            {
                if (LinkedParameter != null)
                    LinkedParameter.Value = (T)port.Value;

                Value = (T)port.Value;
            }
            else
            {
                if (LinkedParameter != null)
                    Value = (T)LinkedParameter.Value;

                port.Value = Value;
            }

            yield return true;
        }

        public override void OnDrawAttributesGUI(out bool updateUI)
        {
            updateUI = false;
#if UNITY_EDITOR
            EditorGUI.BeginChangeCheck();
            IsInNode = EditorGUILayout.ToggleLeft("In Node ", IsInNode);
            if (EditorGUI.EndChangeCheck())
            {
                Init();

                updateUI = true;
            }
#endif
        }

        public override void OnEditorUpdate()
        {
#if UNITY_EDITOR
            if (LinkedParameter != null)
            {
                Value = (T)LinkedParameter.Value;
                mName = LinkedParameter.Name;
            }

            if (mOutPortList.Count > 0 && mOutPortList[0] != null)
                mOutPortList[0].Name = Value.ToString();
#endif
        }
    }
}
